import { importFromOrigin } from './common.js'

export const formatNextTick = (str) => {
  str = str.trim()
  if (!str) return ''
  const isHaveNextTick = str.search(/this\.\$nextTick/) >= 0
  if (isHaveNextTick) {
    importFromOrigin('nextTick')
    const formattedStr = str.match(/^([\s\S]*?)?this\.\$nextTick\(\)\.then\((async\s?)?\(\)\s?=>\s?\{([\s\S]*)\s*?\}\)([\s\S]*?)?$/)

    if (formattedStr) {
      return {
        str: `${formattedStr[1] || ''}await nextTick()
      ${formattedStr[3] || ''}
      ${formattedStr[4] || ''}`,
        isAsync: true,
      }
    } else {
      // console.log('normal', str.replace(/await\s+this\.\$nextTick/, 'await nextTick'))
      return str.replace(/await\s+this\.\$nextTick/g, 'await nextTick')
    }
  } else {
    return { str, isAsync: false }
  }
}
